<?php
namespace app\store\model;

class Card extends Base
{
    /**
     * 列表
     */
    public function index()
    {
        $db = $this->dbConn($this->dbStoreCard)
            ->where(['del' => 0]);
        $total = $db->count();
        $res = $db->order('id', 'desc')
            ->select()->toArray();
        if (!count($res)) {
            return $this->toback(0, '', [], 0);
        }
        $arys = [];
        foreach ($res as $v) {
            $storeOne = $this->dbConn($this->dbStoreUser)
                ->where('store_user_id', $v['store_id'])
                ->find();
            $shop_name = $storeOne ? $storeOne['user_name'] : '-';
            $uOne = $this->dbConn($this->dbUser)
                ->where('user_id', $v['uid'])
                ->find();
            $uname = $uOne ? $uOne['nickName'] : '-';
            $arys[] = [
                'id' => $v['id'],
                'serial' => $v['serial'],
                'cardno' => $v['cardno'],
                'shop_name' => $shop_name,
                'uname' => $uname,
                'realname' => $v['realname'],
                'phone' => $v['phone'],
                'amount' => $this->toNumber($v['amount']),
                'addtime' => $v['addtime'],
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }

    /**
     * 充值列表
     */
    public function rechargeList($card_id)
    {
        $cardOne = $this->dbConn($this->dbStoreCard)
            ->where(['id' => $card_id])
            ->find();
        if (!$cardOne) {
            return $this->toback(-2, '卡不存在');
        }
        $total = $this->dbConn($this->dbCostList)
            ->where(['del' => 0, 'card_id' => $card_id, 'is_refund' => 0])
            ->count();
        $res = $this->dbConn($this->dbCostList)
            ->where(['del' => 0, 'card_id' => $card_id, 'is_refund' => 0])
            ->order('id', 'desc')
            ->select()->toArray();
        if (!count($res)) {
            return $this->toback(0, '', [], 0);
        }
        $types = $this->cardTypes;
        $arys = [];
        foreach ($res as $v) {
            $typeName = array_key_exists($v['type'], $types) ? $types[$v['type']] : '-';
            $operName = $v['oper']==1 ? '+' : '-';
            $arys[] = [
                'id' => $v['id'],
                'serial' => $cardOne['serial'],
                'cardno' => $cardOne['cardno'],
                'type_name' => $typeName,
                'amount' => $operName.$this->toNumber($v['amount']),
                'addtime' => $v['addtime'],
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }
}